package com.lizhenhua.fmmall.service.serviceImpl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lizhenhua.fmmall.entity.CategoryIndex;
import com.lizhenhua.fmmall.entity.CategoryVo;
import com.lizhenhua.fmmall.mapper.CategoryMapper;
import com.lizhenhua.fmmall.service.CategoryService;
import com.lizhenhua.fmmall.vo.ResStatus;
import com.lizhenhua.fmmall.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    private ObjectMapper objectMapper = new ObjectMapper();
   @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Override
    public List<CategoryVo> selectAllCategories() {
        return categoryMapper.selectAllCategorys();
    }


    @Override
    public ResultVo selectAllCategories2(int parentId) {
        List<CategoryVo> categoryVos = null;
        try {
            String s = stringRedisTemplate.boundValueOps("categoryVos").get();
            if (s != null) {
                JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, CategoryVo.class);
                categoryVos = objectMapper.readValue(s, javaType);
                return new ResultVo(ResStatus.OK,"success",categoryVos);
            } else {
                categoryVos = categoryMapper.selectAllCategorys();

                String s1 = objectMapper.writeValueAsString(categoryVos);
                stringRedisTemplate.boundValueOps("categoryVos").set(s1);
                stringRedisTemplate.boundValueOps("categoryVos").expire(1, TimeUnit.DAYS);
                return new ResultVo(ResStatus.NO,"fail",categoryVos);
            }
        } catch (JsonProcessingException e) {
            System.out.println("转换异常");
            return new ResultVo(ResStatus.NO,"字符串转换异常",categoryVos);
        }


    }

    /**
     * 查询类别分类包含三个等级
     * @return
     */
    @Override
    public ResultVo selectFirstLevel() {


        List<CategoryIndex> categoryIndices = categoryMapper.selectFirstLevel();
        return new ResultVo(ResStatus.OK, "success", categoryIndices);
    }
}
